# -*- coding:utf-8 -*-


import time
import json
import config
import pymongo
from scrapy import Spider
from scrapy.http import Request


class BithumbExchange(Spider):
    name = 'bithumb'

    handle_httpstatus_list = [503, 429]

    def __init__(self, name=None, **kwargs):
        super(BithumbExchange, self).__init__(name, **kwargs)

        self.exchange_pair = [{'pair_name': 'BCH_KRW'}, {'pair_name': 'BTC_KRW'}, {'pair_name': 'BTG_KRW'},
                              {'pair_name': 'DASH_KRW'}, {'pair_name': 'ELF_KRW'}, {'pair_name': 'EOS_KRW'},
                              {'pair_name': 'ETC_KRW'}, {'pair_name': 'ETH_KRW'}, {'pair_name': 'ICX_KRW'},
                              {'pair_name': 'LTC_KRW'}, {'pair_name': 'MITH_KRW'}, {'pair_name': 'QTUM_KRW'},
                              {'pair_name': 'TRX_KRW'}, {'pair_name': 'VEN_KRW'}, {'pair_name': 'XMR_KRW'},
                              {'pair_name': 'XRP_KRW'}, {'pair_name': 'ZEC_KRW'}]

        # 连接mongodb
        # client = pymongo.MongoClient('localhost', 27017)
        client = pymongo.MongoClient('47.254.26.182', 27017)
        self.db = client.bt_news

    def start_requests(self):
        for pair in self.exchange_pair:
            pair = pair.get('pair_name').replace('_', '/')
            # https://api.bithumb.com/public/ticker/ZEC/KRW
            url = 'https://api.bithumb.com/public/ticker/%s' % pair

            yield Request(
                url=url,
                dont_filter=True,
                headers={
                    'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36'
                },
                meta={
                    'exchange_pair': pair
                },
                callback=self.exchange_info
            )

    def exchange_info(self, response):
        # 获取json中的数据，对应交易所信息
        body = json.loads(response.body)
        data = body.get('data')

        exchange_pair = response.meta.get('exchange_pair')
        # 交易对
        pair_name = str(exchange_pair.split('/')[0]).upper()
        variual_pair = str(exchange_pair.split('/')[1]).upper()

        # 交易所名称
        exchange_name = 'bithumb'

        # 买家
        buy = data.get('sell_price')

        # 卖价
        sell = data.get('buy_price')

        # 最高价
        high = data.get('max_price')

        # 最低价
        low = data.get('min_price')

        # 成交量
        vol = data.get('volume_1day')

        # 时间
        okcoin_time = data.get('date')

        # 最新成交价
        last = data.get('opening_price')

        # 入库mongo
        data = {
            'exchange_name': exchange_name,
            'variual_coin_name': pair_name,
            'variual_pair': variual_pair,
            # 'market_value': market_value,
            'buy': buy,
            'sell': sell,
            'high': high,
            'low': low,
            'last': last,
            'vol': vol,
            'time': okcoin_time,
            # 'roportion': roportion,
            # 'hasklin': hasklin,
            # 'change1d': change1d,
            'updatetime': time.localtime()
        }

        # pairs = [pair_name, variual_pair]
        # for pair in pairs:
        #     display_name = pair
        #
        #     data_pair = {
        #         'display_name': display_name
        #     }
        #
        #     self.db.bt_virtual_coin.update_one(
        #         {'display_name': display_name},
        #         {'$set': data_pair}, upsert=True)

        # 入库mongo
        if response.status == 200:
            self.db.bt_coin.update_one({'exchange_name': exchange_name, 'variual_coin_name': pair_name, 'variual_pair': variual_pair},
                                       {'$set': data}, upsert=True)


        # 循环更新数据
        # https://api.bithumb.com/public/ticker/ZEC/KRW

        for pair in self.exchange_pair:
            pair = pair.get('pair_name').replace('_', '/')
            # https://api.bithumb.com/public/ticker/ZEC/KRW
            url = 'https://api.bithumb.com/public/ticker/%s' % pair
            # url = response.url

            yield Request(
                url=url,
                dont_filter=True,
                headers={
                    'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36',
                },
                meta={
                    'exchange_pair': exchange_pair
                },
                callback=self.exchange_info
            )


'''
每三秒更新mongo中的数据
'''